package com.javaweb.filter;

import com.javaweb.common.DispatcherTool;
import com.javaweb.common.NullableTool;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebFilter(filterName = "FilterSimpleAuth"
          /*  urlPatterns = {"/*"}*/
)
public class FilterSimpleAuth implements Filter {
    private static final List<String> EXCLUSIVE_URLR = List.of(
                  "login.jsp", "register.jsp","message.jsp",
                   "/upload", "/static","/images",
                 "loginServlet", "registerServlet") ;
    public static final String USER_ATTR_NAME = "user" ;
    @Override
    public void destroy() {
    }
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest)req ;
        if (! isSafeRequest(request) ) {
            if (! isLogin(request)) {
                System.out.println("[INFO] the request was BLOCKED : ");
                DispatcherTool.indirectForwardToClient(request,
                                                    (HttpServletResponse) resp,
                        "01/servlet/login.jsp",
                                                        "未验证用户！") ;
                return ;
            }

        }
        System.out.println("[INFO] authFilter PASS the request.") ;
        chain.doFilter(req, resp);
    }
    @Override
    public void init(FilterConfig config) throws ServletException {
        System.out.println("[INFO] SimpleAuthFilter was initialized .") ;
    }

    private boolean isSafeRequest(HttpServletRequest req) {
        String requestUrl = req.getRequestURL().toString();
        String contextPath = req.getContextPath() ;
        System.out.println("[INFO] authFiler got request : " + requestUrl) ;

        for (String url : EXCLUSIVE_URLR) {
            if (requestUrl.contains(url)) {
                return true ;
            }
        }
        return false ;
    }

    private boolean isLogin(HttpServletRequest req) {
        HttpSession session = req.getSession() ;
        return ! NullableTool.isNull(session.getAttribute(USER_ATTR_NAME) );
    }

}
